/**
 * Display debug message in the console.
 */
function seesDebug(msg) {
//     var consoleService = Components.classes["@mozilla.org/consoleservice;1"]
//                          .getService(Components.interfaces.nsIConsoleService);
//     consoleService.logStringMessage("seesmicsidebar: " + msg);
    window.dump("seesmicsidebar: " + msg + "\n");
}


/**
 * This function is called when seesmicsidebar sidebar is toggled and loads url in the sidebar if it is open.
 */
function seesLoadUrlInSidebar()  {
    var sidebar = top.document.getElementById("sidebar");
    var broadcaster = top.document.getElementById('viewSidebar');

    if (broadcaster.hasAttribute('checked')) {
        sidebar.style.minWidth = '200px';
        sidebar.style.width = '200px';

        sidebar.contentWindow.addEventListener("DOMContentLoaded", seesContentLoaded,
                                               false);

        sidebar.loadURI("http://www.purkiss.com/seesmicsidebar/index_dev.php");
    }
}


/**
 * Modify existing links in the documents and setup handler for
 * future document modifications.
 */
function seesContentLoaded () {
    seesConvertLinks();

    // Add handler for subsequent modifications
    var sidebar = top.document.getElementById("sidebar");
    var table = sidebar.contentDocument.getElementById("sees_table");
    table.addEventListener("DOMNodeInserted", seesConvertLinks,
                                           false);
}


/**
 * Return function that opens url in a new tab
 */
function seesCreateOpenFunction(url) {
    return function() {
        seesDebug("Opening in a new tab " + url);
        gBrowser.selectedTab = gBrowser.addTab(url);
    };
}


/**
 * Converts links in currently open document in the sidebar so that they would open
 * in the new tab.
 */
function seesConvertLinks() {
    seesDebug("Convert links called");
    var sidebar = top.document.getElementById("sidebar");
    var doc = sidebar.contentDocument;

    var all_links = new Array();

    var links = doc.evaluate("//a", doc, null, XPathResult.ANY_TYPE, null);
    var link = links.iterateNext();
    while (link) {
        all_links.push(link);
        link = links.iterateNext();
    }

    for (var i = 0; i < all_links.length; i++) {
        link = all_links[i];
        if (!link.hasAttribute('onclick') &&
            link.hasAttribute('href') && link.getAttribute('href').match(/^\s*https?:/)) {
            var target = link.getAttribute('href');
            seesDebug("Redefining handler for " + target);
            // Mark the link to not add handler twice
            link.setAttribute('onclick', 'return false;');
            link.removeAttribute('target');
            link.addEventListener('click', seesCreateOpenFunction(target), true);
        }
    }
}


/**
 * This function adds seesmicsidebar icon to the navbar if it is not present there.
 */
function seesAddIconToNavbar() {
    var toolbox = document.getElementById("navigator-toolbox");
    var toolboxDocument = toolbox.ownerDocument;

    var hasSeesmisidebarButton = false;
    for (var i = 0; i < toolbox.childNodes.length; ++i) {
    	var toolbar = toolbox.childNodes[i];
    	if (toolbar.localName == "toolbar" && toolbar.getAttribute("customizable") == "true" ) {
    	    if (toolbar.currentSet.indexOf("seesmicsidebar-button") > -1)
    		hasSeesmisidebarButton = true;
    	}
    }

    if (!hasSeesmisidebarButton) {
    	for (var i = 0; i < toolbox.childNodes.length; ++i) {
    	    toolbar = toolbox.childNodes[i];
    	    if (toolbar.localName == "toolbar" &&  toolbar.getAttribute("customizable") == "true"
                && toolbar.id == "nav-bar") {
    	   	var newSet = "";
    	   	var child = toolbar.firstChild;
    	   	while (child) {
    	   	   if (!hasSeesmisidebarButton && (child.id=="seesmicsidebar-button" || child.id=="urlbar-container")) {
    		      newSet += "seesmicsidebar-button,";
    		      hasSeesmisidebarButton = true;
    	   	   }

    		    newSet += child.id + ",";
    		    child = child.nextSibling;
    		}

    		newSet = newSet.substring(0, newSet.length-1);
    		toolbar.currentSet = newSet;

    		toolbar.setAttribute("currentset", newSet);
    		toolboxDocument.persist(toolbar.id, "currentset");
    		BrowserToolboxCustomizeDone(true)
    		break;
    	    }
    	}
    }
}


window.addEventListener("load", seesAddIconToNavbar, false);
